#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime

from farado.items.user import User
from farado.items.role import Role
from farado.items.rule import Rule
from farado.items.user_role import UserRole

from farado.items.project import Project
from farado.items.version import Version
from farado.items.workflow import Workflow
from farado.items.state import State
from farado.items.edge import Edge

from farado.items.board import Board
from farado.items.board_column import BoardColumn

from farado.items.issue import Issue
from farado.items.issue_kind import IssueKind

from farado.items.field import Field
from farado.items.field_kind import FieldKind, ValueTypes

from farado.database.meta_item_manager import MetaItemManager
from farado.project_manager import ProjectManager
from farado.permission_manager import PermissionFlag
from farado.general_manager_holder import gm_holder

from farado.config import farado_config


def main():
    data_creator = DefaultDataCreator()
    data_creator.create_users()
    data_creator.create_workflow()
    data_creator.create_board()
    data_creator.create_issues()

class DefaultDataCreator:
    def __init__(self) -> None:
        self.meta_item_manager = MetaItemManager(farado_config['database']['connection_string'])
        self.project_manager = ProjectManager()
        gm_holder.set_meta_item_manager(self.meta_item_manager)
        gm_holder.set_project_manager(self.project_manager)
        self.save_item = self.project_manager.save_item

    def create_users(self):
        user = User(
            'admin',
            'Иван',
            'Иванович',
            'Сидоров',
            'ivan.sidorov@ya.ru',
            password="admin",
        )
        self.save_item(user)

        role = Role('Администратор')
        role.rules.append(Rule(
                caption='Правило суперадмина',
                is_admin=True,
                project_rights=PermissionFlag.deleter
        ))
        self.save_item(role)
        self.save_item(UserRole(user_id=user.id, role_id=role.id))

    def create_workflow(self):
        workflow = Workflow(caption="Бизнес-процесс")
        state_01 = State(caption="Отрыто")
        state_02 = State(caption="В работе")
        state_03 = State(caption="Тестирование")
        state_04 = State(caption="Выполнено")
        workflow.states.append(state_01)
        workflow.states.append(state_02)
        workflow.states.append(state_03)
        workflow.states.append(state_04)
        self.save_item(workflow)
        workflow.edges.append(Edge(state_01.id, state_02.id))
        workflow.edges.append(Edge(state_02.id, state_03.id))
        workflow.edges.append(Edge(state_03.id, state_04.id))
        self.save_item(workflow)
        self.default_state_id = state_01.id
        self.state_id_02 = state_02.id
        self.state_id_03 = state_03.id
        self.state_id_04 = state_04.id
        self.default_workflow_id = workflow.id

    def create_board(self):
        board = Board(
                caption="Основная доска",
                workflow_id=self.default_workflow_id)
        board.board_columns.append(
            BoardColumn(
                state_id=self.default_state_id,
                caption='Беклог',
                order=1
            ))
        board.board_columns.append(
            BoardColumn(
                state_id=self.state_id_02,
                caption='В процессе',
                order=2
            ))
        board.board_columns.append(
            BoardColumn(
                state_id=self.state_id_03,
                caption='На проверке',
                order=3
            ))
        board.board_columns.append(
            BoardColumn(
                state_id=self.state_id_04,
                caption='Завершено',
                order=4
            ))
        self.save_item(board)

    def create_issues(self):
        issue_kind = IssueKind("Задача")
        issue_kind.workflow_id = self.default_workflow_id
        issue_kind.default_state_id = self.default_state_id
        issue_kind.field_kinds.append(
            FieldKind(
                "Исполнитель",
                ValueTypes.user_id,
                "Issue developer"
            )
        )
        issue_kind.field_kinds.append(
            FieldKind(
                "Целочисленное значение",
                ValueTypes.integer,
                "Some integer value"
            )
        )
        self.save_item(issue_kind)

        # ====================== #
        project = Project(
            caption="Пример проекта №1",
            content="Пример описательной части проекта №1",
            issues_view_settings='id,kind,state,caption,version,parent,field_kind_1,field_kind_2',
        )
        project.versions.append(Version(caption='1.2.3'))
        project.versions.append(Version(caption='1.2.4'))
        project.versions.append(Version(caption='1.3'))

        issue1 = self.project_manager.create_issue(issue_kind.id)
        issue1.caption = "Новая деятельность"
        issue1.content = "Выполнить новую деятельность пока не будет готово"
        print(issue1.fields)
        issue1.field(1).value = 1
        issue1.version_id = 1
        project.issues.append(issue1)
        self.save_item(project)

        issue2 = self.project_manager.create_issue(issue_kind.id)
        issue2.caption = "Дополнительная деятельность"
        issue2.content = "Доделать всю дополнительную деятельность до конца"
        issue2.parent_id = issue1.id
        issue2.version_id = 1
        project.issues.append(issue2)
        self.save_item(project)

        issue3 = self.project_manager.create_issue(issue_kind.id)
        issue3.caption = "Та самая деятельность"
        issue3.content = "Сделать чтобы работало"
        issue3.parent_id = issue1.id
        issue3.version_id = 2
        project.issues.append(issue3)
        self.save_item(project)

        # ====================== #
        project2 = Project(
            caption="Пример проекта №2",
            content="Пример описательной части проекта №2",
            issues_view_settings='id,kind,state,caption,parent',
        )
        project2.issues.append(
            Issue(
                "Ещё одна важная деятельность",
                "Issue content 21",
                issue_kind_id=1,
            )
        )
        project2.issues.append(
            Issue(
                "Итоговая завершающая деятельность",
                "Issue content 22",
                issue_kind_id=1,
            )
        )
        self.save_item(project2)

if __name__ == '__main__':
    main()
